package com.seven.thread;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.springframework.http.ResponseEntity;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author sevenDay
 * @classname SevenRateLimiter
 * @description: 限流算法的实现
 * @date 2018/3/13
 */
public class SevenRateLimiter {

    private static Semaphore semaphore ;

    public static long permit = 50;

    private LoadingCache<Long, AtomicLong> counter =
            CacheBuilder.newBuilder()
            .expireAfterWrite(2,TimeUnit.SECONDS)
                    .build(new CacheLoader<Long, AtomicLong>() {
        @Override
        public AtomicLong load(Long seconds) throws Exception {
            return new AtomicLong(0);
        }
    });
    public ResponseEntity getData() throws ExecutionException {

        //得到当前秒
     /*   long currentSeconds = System.currentTimeMillis() / 1000;
        if(counter.get(currentSeconds).incrementAndGet() > permit) {
            return ResponseEntity.builder().code(404).msg("访问速率过快").build();
        }*/
        //业务处理
        return null;
    }

    public SevenRateLimiter(){
        semaphore = new Semaphore(10);
    }
    public static  void acquire(){
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void release(){
        semaphore.release();
       /* Student sy = new Student();*/

    }
}
